package cn.edu.nju.software.android.activity;

import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.keep.AccessTokenKeeper;

import cn.edu.nju.software.android.layoutHelper.FriendsLayoutHelper;
import cn.edu.nju.software.android.layoutHelper.LayoutHelper;
import cn.edu.nju.software.android.layoutHelper.MessagesLayoutHelper;
import cn.edu.nju.software.android.layoutHelper.SettingsLayoutHelper;
import cn.edu.nju.software.android.layoutHelper.TimelineLayoutHelper;
import cn.edu.nju.software.android.model.User;
import cn.edu.nju.software.android.service.MessagesService;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class MainActivity extends Activity {
	public static Weibo mWeibo;
	public static final String CONSUMER_KEY = "643614169";
	private static final String REDIRECT_URL = "https://api.weibo.com/oauth2/default.html";
	public static Oauth2AccessToken accessToken;
	public static final String TAG = "sinasdk";
	public static long uid;
	public static User user;
	private LayoutHelper helper;
	private Menu menu;


	private Handler uidhandler = new Handler(){
		public void handleMessage(Message msg) {
			Bundle data = msg.getData();
			uid = data.getLong("uid");
			User.getUserInfo(uid, userhandler);
		};
	};

	private Handler userhandler = new Handler(){
		public void handleMessage(Message msg) {
			Bundle data = msg.getData();
			user = (User) data.getSerializable("user");
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mWeibo = Weibo.getInstance(CONSUMER_KEY, REDIRECT_URL);
		accessToken = AccessTokenKeeper.readAccessToken(this);
		if(accessToken.isSessionValid()){
			User.getUID(uidhandler);
			init();
		} else {
			mWeibo.authorize(MainActivity.this, new AuthDialogListener());
		}
	}

	@Override 
	public boolean onKeyDown(int keyCode, KeyEvent event) {         

		//按下键盘上返回按钮

		if(keyCode == KeyEvent.KEYCODE_BACK){

			new AlertDialog.Builder(this) 
			.setIcon(R.drawable.small_logo) 
			.setTitle(R.string.quit)
			.setMessage(R.string.quit_desc) 
			.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { 
				@Override 
				public void onClick(DialogInterface dialog, int which) { 
				} 
			}) 
			.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener()

			{ 
				public void onClick(DialogInterface dialog, int whichButton) { 
					android.os.Process.killProcess(android.os.Process.myPid());
				} 
			}).show(); 

			return true; 
		}else{        
			return super.onKeyDown(keyCode, event); 
		} 
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		this.menu = menu;
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case R.id.post:
			Intent intent = new Intent(MainActivity.this, PostActivity.class);
			startActivity(intent);
			break;
		case R.id.refresh:
			if(helper instanceof TimelineLayoutHelper){
				((TimelineLayoutHelper) helper).onRefresh();
			}
			break;
		default:
			return true;
		}
		return false;
	}

	private void init() {
		setContentView(R.layout.activity_main);
		setTimeline();
		setTabListener();
		Intent intent=new Intent(this, MessagesService.class);
		startService(intent);
	}

	private void clearMenu() {

		ImageView home = (ImageView) findViewById(R.id.timeline);
		home.setBackgroundColor(getResources().getColor(R.color.dark_theme));

		ImageView message = (ImageView) findViewById(R.id.messages);
		message.setBackgroundColor(getResources().getColor(R.color.dark_theme));

		ImageView friends = (ImageView) findViewById(R.id.friends);
		friends.setBackgroundColor(getResources().getColor(R.color.dark_theme));

		ImageView settings = (ImageView) findViewById(R.id.settings);
		settings.setBackgroundColor(getResources().getColor(R.color.dark_theme));

	}

	private void clearContent() {
		LinearLayout tab_layout = (LinearLayout) findViewById(R.id.tab_layout);
		tab_layout.removeAllViews();
	}

	/**
	 * 此方法显示首页微博列表
	 */
	private void setTimeline() {
		LinearLayout tab_layout = (LinearLayout) findViewById(R.id.tab_layout);
		View timeline = View.inflate(this, R.layout.layout_timeline, null);
		tab_layout.addView(timeline);
		//此处调用显示微博列表代码
		helper = new TimelineLayoutHelper(this);
		helper.initialize(timeline);
	}

	/**
	 * 此方法显示消息列表
	 */
	private void setMessages() {
		LinearLayout tab_layout = (LinearLayout) findViewById(R.id.tab_layout);
		View messages = View.inflate(this, R.layout.layout_messages, null);
		tab_layout.addView(messages);
		//此处调用显示微博列表代码
		helper = new MessagesLayoutHelper(this);
		helper.initialize(messages);
	}

	/**
	 * 此方法显示好友列表
	 */
	private void setFriends() {
		LinearLayout tab_layout = (LinearLayout) findViewById(R.id.tab_layout);
		View friends = View.inflate(this, R.layout.layout_friends, null);
		tab_layout.addView(friends);
		//此处调用显示微博列表代码
		helper = new FriendsLayoutHelper(this);
		helper.initialize(friends);
	}

	/**
	 * 此方法显示设置列表
	 */
	private void setSettings() {
		LinearLayout tab_layout = (LinearLayout) findViewById(R.id.tab_layout);
		View settings = View.inflate(this, R.layout.layout_settings, null);
		tab_layout.addView(settings);
		//此处调用显示微博列表代码
		helper = new SettingsLayoutHelper(this);
		helper.initialize(settings);
	}

	/**
	 * 此方法设置分页按钮监听
	 */
	private void setTabListener() {
		ImageView timeline = (ImageView) findViewById(R.id.timeline);
		timeline.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {     
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					clearMenu();
					v.setBackgroundColor(getResources().getColor(R.color.dark_touch));  
					clearContent();
					setTimeline();
					menu.removeItem(R.id.post);
					menu.removeItem(R.id.refresh);
					getMenuInflater().inflate(R.menu.main, menu);
				}
				return false;
			}
		});

		ImageView message = (ImageView) findViewById(R.id.messages);
		message.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {     
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					clearMenu();
					v.setBackgroundColor(getResources().getColor(R.color.dark_touch)); 
					clearContent();
					setMessages();
					menu.removeItem(R.id.post);
					menu.removeItem(R.id.refresh);
				}
				return false;
			}
		});

		ImageView friends = (ImageView) findViewById(R.id.friends);
		friends.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {     
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					clearMenu();
					v.setBackgroundColor(getResources().getColor(R.color.dark_touch));  
					clearContent();
					setFriends();
					menu.removeItem(R.id.post);
					menu.removeItem(R.id.refresh);
				}
				return false;     
			}
		});

		ImageView settings = (ImageView) findViewById(R.id.settings);
		settings.setOnTouchListener(new OnTouchListener(){     
			@Override    
			public boolean onTouch(View v, MotionEvent event) {     
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					clearMenu();
					v.setBackgroundColor(getResources().getColor(R.color.dark_touch));  
					clearContent();
					setSettings();
					menu.removeItem(R.id.post);
					menu.removeItem(R.id.refresh);
				}
				return false;
			}
		});
	}

	class AuthDialogListener implements WeiboAuthListener {

		@Override
		public void onComplete(Bundle values) {
			String token = values.getString("access_token");
			String expires_in = values.getString("expires_in");
			accessToken = new Oauth2AccessToken(token, expires_in);
			if (accessToken.isSessionValid()) {
				AccessTokenKeeper.keepAccessToken(MainActivity.this, accessToken);
				User.getUID(uidhandler);
				Toast.makeText(MainActivity.this, "认证成功", Toast.LENGTH_SHORT).show();
				init();
			}
		}

		@Override
		public void onError(WeiboDialogError e) {
			Toast.makeText(getApplicationContext(),
					"Auth error : " + e.getMessage(), Toast.LENGTH_LONG).show();
		}

		@Override
		public void onCancel() {
			Toast.makeText(getApplicationContext(), "Auth cancel",
					Toast.LENGTH_LONG).show();
		}

		@Override
		public void onWeiboException(WeiboException e) {
			Toast.makeText(getApplicationContext(),
					"Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)
					.show();
		}

	}

}
